package com.iflytek.uoamp.agent.monitor.find.imp;

import com.iflytek.uoamp.agent.core.sender.monitorsender.responseObj.Program;
import com.iflytek.uoamp.agent.core.sender.monitorsender.responseObj.ProgramType;
import com.iflytek.uoamp.agent.monitor.find.Finder;
import com.iflytek.uoamp.agent.monitor.mcagent.MCAgentConfig;

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @ClassName: FindWinMonitorItem
 * @Description: windows组件自发现
 * @author qinanyuan
 * @date 2017年4月13日 上午11:25:11
 */
public class FindWinMonitorItem implements Finder {
	private static final String[] EXE_NAME = {"mysqld.exe", "httpd.exe" , "inetinfo.exe" , "kettle.exe"};
	private List<String> list;
	public List<String> getList() {
		return list;
	}

	public void setList(List<String> list) {
		this.list = list;
	}

	@Override
	public List<Program> getMonitorItems() {
		List<Program> proList = new ArrayList<Program>();
		try {
			for (int i = 0; i < EXE_NAME.length; i++) {
				Program cprogram = new Program();
				String path = "win";
				Map<String, Object> resultMap = getTaskDetail(EXE_NAME[i]);
				if (resultMap == null || resultMap.isEmpty()) {
					continue;
				}
				String cpname = "";
				if(EXE_NAME[i].equals("mysqld.exe")){
					cpname = "(windows)mysql";
				}else if(EXE_NAME[i].equals("httpd.exe")){
					cpname = "(windows)iis";
				}else if(EXE_NAME[i].equals("inetinfo.exe")){
					cpname = "(windows)apache";
				}else if(EXE_NAME[i].equals("kettle.exe")){
					cpname = "(windows)kettle";
				}
				cprogram.setIp(MCAgentConfig.getInstance().getMonitoredPointIp());
				cprogram.setType(ProgramType.COM);
				cprogram.setCpname(cpname);
				cprogram.setPath(path);
				cprogram.setFlags(Arrays.asList("0"));
				proList.add(cprogram);
			}

		} catch (Exception e) {
			Logger.getRootLogger().error("getMonitorItems fail!" , e);
		}
		return proList;
	}

	
	public static Map<String, Object> getTaskDetail(String taskName){
        String[] cmdStr = {"cmd", "/C", "wmic process where name='" + taskName + "' list full"};
        Map<String, Object> map = new HashMap<String, Object>();
        try {
        	map = execCommand(cmdStr);
        } catch (Exception e) {
        	Logger.getRootLogger().error("关闭服务失败！" , e);
        }
        return map;
	}
	
	private static Map<String, Object> execCommand(String[] cmdStr){
		Process p = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			p = Runtime.getRuntime().exec(cmdStr);
			map = printStream(p.getInputStream());
		} catch (IOException e) {
			Logger.getRootLogger().error("启动服务失败!" , e);
		} catch (Exception e) {
			Logger.getRootLogger().error("获取执行结果失败!" , e);
		} finally {
			if (p != null) {
				p.destroy();
			}
		}
		return map;
	}
	
    private static Map<String, Object> printStream(InputStream input) { //InputStream input  final Process proc
        if(null == input){
        	return null;
        }
        InputStreamReader isr = new InputStreamReader(input); //proc.getInputStream()
        BufferedReader br = new BufferedReader(isr);
        Map<String, Object> map = new HashMap<String, Object>();
        String str = null;
        String[] arrStr = null;
        try {
            while ((str = br.readLine()) != null) {
                if (!str.equals("")) {
                    if (str.contains("=")) {
                        arrStr = str.split("=");
                        str = str.endsWith("=") ? "" : arrStr[1];
                        map.put(arrStr[0], str);
                    } else {
                        map.put(str, null);
                    }
                }
            }
        } catch (IOException e) {
        	Logger.getRootLogger().error("关闭文件流失败！" , e);
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
                input.close();
            } catch (IOException e) {
            	Logger.getRootLogger().error("关闭文件流失败！" , e);
            }
        }
        return map;
    }
  
    
    private static String printErrorStream(InputStream input) throws IOException {
    	if(null == input){
    		return null;
    	}
        InputStreamReader reader = new InputStreamReader(input);
        BufferedReader br = new BufferedReader(reader);
        StringBuffer msg = new StringBuffer();
        String str = "";
        try {
            while ((str = br.readLine()) != null) {
                if (!str.equals("")) {
                	msg.append(str + ",");
                }
            }
            if (msg.toString().endsWith(",")) {
                msg.substring(0, msg.lastIndexOf(","));
            }
            return msg.toString();
        } catch (IOException e) {
        	System.out.println("读取错误信息失败!" + e);
            throw e;
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (reader != null) {
                    reader.close();
                }
                input.close();
            } catch (IOException e) {
            	System.out.println("关闭文件流失败！" + e);
                throw e;
            }
        }
    }
}